package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {

    @Override
    public List<CourseCategoryTreeDto> courseCategoryTree() {

        LambdaQueryWrapper<CourseCategory> wrapper = new LambdaQueryWrapper<>();
        //先对分类进行排序
        wrapper.orderByAsc(CourseCategory::getIsLeaf);
        //根节点不参与
        wrapper.ne(CourseCategory::getParentid,0);
        List<CourseCategory> list = this.list(wrapper);
        //一级节点map
        Map<String, CourseCategoryTreeDto> map = new HashMap<>();
        //结果集
        List<CourseCategoryTreeDto> result=new ArrayList<>();
        //收集根节点
        for (CourseCategory item : list) {
            CourseCategoryTreeDto courseCategoryTreeDto = new CourseCategoryTreeDto();
            BeanUtils.copyProperties(item,courseCategoryTreeDto);
            //根节点
            if(item.getParentid().equals("1")){
                map.put(item.getId(),courseCategoryTreeDto);
            }else{
                //从map中找到父节点
                String pid=item.getParentid();
                CourseCategoryTreeDto parentDto = map.get(pid);
                //父节点的孩子
                List<CourseCategoryTreeDto> childrenNode = parentDto.getChildrenTreeNodes();
                if(childrenNode!=null){
                    childrenNode.add(courseCategoryTreeDto);
                }else {
                    childrenNode=new ArrayList<>();
                    childrenNode.add(courseCategoryTreeDto);
                }
                //将旧的一级分类删除
                result.remove(parentDto);
                parentDto.setChildrenTreeNodes(childrenNode);
                result.add(parentDto);
            }
        }
        return result;
    }
}
